 <?php
					
include 'conn.php';		

$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);

//获取
if($_GET['lx']=='getTreeTableData'){
	
	$sql="select * from menu where parent_id =-1";

	$rows = array();
	$rs =  mysqli_query($con,$sql);
	while($row = $rs->fetch_assoc()){
		
		$result_child = array();
		$result_child=has_child($row['id']);

		if($result_child){
			$row['children']=$result_child;
		}else{
			$row['children']=[];
		}
		
		array_push($rows,$row);
		
		// $sql1="select * from menu where parent_id=".$row['id'];	
		// $rs1 =mysqli_query($con,$sql1);	
		// $result1 = array();
		// while($row1 = $rs1->fetch_assoc()){		
		// 	array_push($result1,$row1);
		// }
		// if($result1){
		// 	$row['children']=$result1;
		// }
		// array_push($rows,$row);
	} 
	
	$result["code"] = 200;
	$result["data"] = $rows;
	$result["message"] = "list";
	$result['sql']=$sql;
	echo json_encode($result);

//修改 新增
}elseif($_GET['lx']=='saveEditMenu'){
	
	if($_GET['id']=='999'){

		$sql="UPDATE menu set ";
		foreach ($data as $k => $v) {	

			$sql=$sql. $k . "='" . $v . "',";	
		}		
		$sql=substr($sql,0,-1);		//去除最后一个字符 ','		
		$sql=$sql." where id=".$data['id'];		

		$sql=str_replace(",children='Array'","",$sql); 
							
		// if($data['parent_id']==null){  //parent_id 一级菜单必须为 null
		// 	$sql=str_replace("parent_id=''","parent_id=NULL",$sql);
		// }

		$result["message"] = "修改成功！";
	}else{

		if($_GET['id']!=='root')	//新增一级菜单
			$data['parent_id']=$_GET['id'];		


		$sql="INSERT INTO menu(";
	
		foreach ($data as $k => $v) {		
			$cols=$cols.$k.",";
			$value=$value."'".$v."',";
		}
		$cols=substr($cols,0,-1);	
		$value=substr($value,0,-1);

		$sql=$sql.$cols.")VALUES(".$value.")";

		$result["message"] = "添加成功！";
	}

	mysqli_query($con,$sql);

	$result["code"] = 200;
	$result["data"] = $rows;
	$result['sql']=$sql;
	echo json_encode($result);
	
}elseif($_GET['lx']=='delMenu'){

	$sql="DELETE FROM menu WHERE id=".$data['id'];
	mysqli_query($con,$sql);
	
	$result["code"] = 200;
	$result["message"] = "删除成功！";
	$result['sql']=$sql;
	echo json_encode($result);

}else{

	$result["code"] = 201;
	$result["message"] = "else";
	echo json_encode($result);
	
}

		  
function has_child($id){
	global  $con;

	$result = array();
	$sql="select * from menu where parent_id=".$id;	
	$rs_child =mysqli_query($con,$sql);	
	while($row = $rs_child->fetch_assoc()){
		
		$result_child = array();
		$result_child=has_child($row['id']);
	
		if($result_child){
			$row['children']=$result_child;
		}else{
			$row['children']=[];
		}	
		
		array_push($result,$row);		
	}	
	//echo $sql."<br>";
	return $result;
} 

?>